<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模版名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入模版名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['business:freightTemplate:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['business:freightTemplate:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:freightTemplate:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="freightTemplateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模版名称" align="center" prop="name" />
      <!--      <el-table-column label="模版说明" align="center" prop="descinfo" />-->
      <el-table-column label="计费方式" align="center" prop="typeName" />
      <el-table-column label="首件数量" align="center" prop="firstNum" />
      <el-table-column label="首件价格" align="center" prop="firstPrice" />
      <el-table-column label="续件数量" align="center" prop="continueNum" />
      <el-table-column label="续件价格" align="center" prop="continuePrice" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:freightTemplate:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:freightTemplate:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改运费模版对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="freightTemplateRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="模版名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入模版名称" />
        </el-form-item>
        <el-form-item label="模版说明:" prop="descinfo">
          <el-input v-model="form.descinfo" placeholder="请输入模版说明" />
        </el-form-item>
        <el-form-item label="计费方式:">
          <el-radio-group v-model="form.typeId">
            <el-radio label="1" >按件计费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="默认运费:">
          <el-input v-model="form.firstNum" type = "number" style="width:80px; margin-right: 10px; margin-left: 10px" />
          <span>件内,</span>
          <el-input v-model="form.firstPrice" type = "number" style="width:80px; margin-right: 10px; margin-left: 10px"/>
          <span>元，每增加</span>
          <el-input v-model="form.continueNum" type = "number" style="width:80px; margin-right: 10px; margin-left: 10px"/>
          <span>件，增加运费</span>
          <el-input v-model="form.continuePrice" type = "number" style="width:80px; margin-right: 10px; margin-left: 10px"/>
          <span>元</span>
        </el-form-item>
        <!-- 动态表格 -->
        <el-form-item label="" style="margin-top: 20px">
          以下指定地区外，不采用“默认运费”框中只能填写整数。
          <el-table :data="form.detailList"
                    style="width: 100% ; margin-top: 20px" @selection-change="handleSelectionChangeTable" border >
            <!-- 多选列 -->
            <el-table-column type="selection" width="55" />
            <!-- 数据列 -->
            <el-table-column prop="name" label="指定地区" width="120">
              <template #default="{ row }">
                <el-select v-model="row.provinceId" size="small" >
                  <el-option v-for="item in provinceArr" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="首件(件)" width="120">
              <template #default="{ row }">
                <el-input v-model="row.firstNum" type = "number"/>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="首件价格(件)" width="120">
              <template #default="{ row }">
                <el-input v-model="row.firstPrice"  type = "number"/>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="续件(件)" width="120">
              <template #default="{ row }">
                <el-input v-model="row.continueNum" type = "number"/>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="续件价格(件)" width="120">
              <template #default="{ row }">
                <el-input v-model="row.continuePrice"  type = "number"/>
              </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作" width="120">
              <template #default="{ $index }">
                <el-button type="danger" link @click="handleDeleteRow($index)" >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 表格底部按钮 -->
          <div class="table-footer">
            <el-button type="primary" @click="handleAddRow">
              <el-icon><Plus /></el-icon>
              添加指定地区
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FreightTemplate">
import { listFreightTemplate, getFreightTemplate, delFreightTemplate, addFreightTemplate,
  updateFreightTemplate, getCommonAreaList } from "@/api/business/freightTemplate";
import { ref, reactive } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance();

const freightTemplateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const provinceArr = ref([]);//省list

// const typeId= ref('1');
// const form = reactive({
//   typeId:'1',
//   detailList: []
// })

const data = reactive({
  form: {
    typeId:'1',
    detailList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    descinfo: null,
    typeId: null,
    typeName: null,
  },
  rules: {
    // firstNum: [{ required: true, message: "首件不能为空", trigger: "blur" }],
    // firstPrice: [{ required: true, message: "首件金额不能为空", trigger: "blur" }],
    // continueNum: [{ required: true, message: "续件数量不能为空", trigger: "blur" }],
    // continuePrice: [{ required: true, message: "续件金额不能为空", trigger: "blur" }],
  }
});

const { queryParams,form, rules } = toRefs(data);


// 选中的行
const selectedRows = ref([])

// 处理多选
const handleSelectionChangeTable = (val) => {
  selectedRows.value = val
}

// 新增行
const handleAddRow = () => {
  form.value.detailList.push({
    firstNum: '',
    firstPrice: '',
    continueNum: '',
    continuePrice: '',
    provinceId: '',
    provinceName: '',
    id: Date.now() // 使用时间戳作为唯一标识
  })
}

// 删除单行
const handleDeleteRow = (index) => {
  form.value.detailList.splice(index, 1)
}

// 批量删除
const handleBatchDelete = () => {
  const selectedIds = new Set(selectedRows.value.map(item => item.id))
  form.value.detailList = form.value.detailList.filter(item => !selectedIds.has(item.id))
  selectedRows.value = []
}

/** 查询运费模版列表 */
function getList() {
  loading.value = true;
  listFreightTemplate(queryParams.value).then(response => {
    freightTemplateList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    descinfo: null,
    typeId: null,
    typeName: null,
    firstNum: null,
    firstPrice: null,
    continueNum: null,
    continuePrice: null,
    delFlag: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    detailList: []
  };
  proxy.resetForm("freightTemplateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加运费模版";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getFreightTemplate(_id).then(response => {
    // console.log('getFreightTemplate is',response.data)
    form.value = response.data;
    form.value.typeId = '' + form.value.typeId;
    form.value.detailList = response.data.detailList ? response.data.detailList : [];
    open.value = true;
    title.value = "修改运费模版";

  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["freightTemplateRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFreightTemplate(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFreightTemplate(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除运费模版编号为"' + _ids + '"的数据项？').then(function() {
    return delFreightTemplate(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/freightTemplate/export', {
    ...queryParams.value
  }, `freightTemplate_${new Date().getTime()}.xlsx`)
}

//获取省份
function getProvinceList(parentId){
  getCommonAreaList(parentId).then((response) => {
    provinceArr.value = response.data;
  }).catch(() => {})
}

getProvinceList(0);
getList();
</script>
